package helper.com.serviceImpl;

import helper.com.exception.CustomException;
import helper.com.res.AjaxResponse;
import helper.com.service.LogService;
import helper.com.utils.Log4j2Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

import static helper.com.utils.FileUtil.inReadToOut;


/**
 * @author 大忽悠
 * @create 2022/5/17 14:36
 */
@Service
@Slf4j
public class LogServiceImp implements LogService {
    @Override
    public AjaxResponse changeLogLevel(String level, String loggerName) {
        try {
            if(!Log4j2Util.isLegal(level)){
                throw new IllegalArgumentException("非法日志级别");
            }
            Log4j2Util.changeLevel(level,loggerName);
        } catch (IOException e) {
            throw new CustomException("日志配置文件不存在");
        }
        return AjaxResponse.success();
    }

    @Override
    public AjaxResponse changeLogFile(String appenderName, String logDir) {
        String oldFileName = Log4j2Util.changeLogFile(appenderName, logDir);
        log.warn("正在将{}[RollingFileAppender]的日志文件存放目录由{}改变为{}",appenderName,oldFileName, logDir);
        return AjaxResponse.success();
    }

    @Override
    public void downLoadLogFile(HttpServletResponse response) {
        doDownLoad(response);
    }

    private void doDownLoad(HttpServletResponse response) {
        BufferedInputStream zpIn=null;
        BufferedOutputStream out=null;
        try {
            zpIn = prepareResponseAndGetInStream(response);
            out = new BufferedOutputStream(response.getOutputStream());
            inReadToOut(zpIn, out);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            Log4j2Util.delLogGzFile();
        }
    }


    private BufferedInputStream prepareResponseAndGetInStream(HttpServletResponse response) throws FileNotFoundException {
        response.setCharacterEncoding("UTF-8");
        // 设置强制下载不打开
        response.setContentType("application/octet-stream");
        //拿到压缩日志文件输入流
        File gzFile = Log4j2Util.getLogGzFile();
        FileInputStream in = new FileInputStream(gzFile);
        // 告知浏览器文件的大小
        response.addHeader("Content-Length", "" + gzFile.length());
        // 设置文件名
        response.addHeader("Content-Disposition", "attachment;fileName=" + gzFile.getName());
        return new BufferedInputStream(in);
    }

}
